package com.ningmengs789.live.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ningmengs789.live.Interface.RequestCallback;
import com.ningmengs789.live.R;
import com.ningmengs789.live.http.OKHttpUtils;
import com.ningmengs789.live.net.utils.NToast;
import com.ningmengs789.live.utils.CommonUtils;
import com.bumptech.glide.Glide;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PromoteActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.tv_title_center)
    TextView tv_title_center;

    @BindView(R.id.promote_iv_qr)
    ImageView promote_iv_qr;

    @BindView(R.id.promote_boon_text)
    TextView promote_boon_text;
    @BindView(R.id.promote_desc_text)
    TextView promote_desc_text;

    @BindView(R.id.promote_ll_share)
    LinearLayout promote_ll_share;

    @BindView(R.id.promote_save_text)
    TextView promote_save_text;
    @BindView(R.id.promote_copy_share)
    TextView promote_copy_share;

    private String link;
    private ClipboardManager myClipboard;
    private ClipData myClip;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isShow = true;
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_promote);
        ButterKnife.bind(this);

        setHeadLayout();
        tv_title_center.setVisibility(View.VISIBLE);
        tv_title_center.setText(getString(R.string.share_look));

        promote_save_text.setOnClickListener(this);
        promote_copy_share.setOnClickListener(this);

        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

        getPromData4ShortVideo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.promote_save_text:
                bitmap = loadBitmapFromViewBySystem(promote_ll_share);
                if (bitmap == null){
                    bitmap = loadBitmapFromView(promote_ll_share);
                }
                saveImg();
                break;
            case R.id.promote_copy_share:
                copy();
                break;
        }
    }

    private void copy() {
        if (link == null){
            NToast.shortToast(this, "复制失败");
            return;
        }
        myClip = ClipData.newPlainText("text", link);
        myClipboard.setPrimaryClip(myClip);
        NToast.shortToast(this, "已复制到剪贴板");
    }

    private static Bitmap loadBitmapFromViewBySystem(View v) {
        if (v == null) {
            return null;
        }
//        v.setDrawingCacheEnabled(false);
        v.destroyDrawingCache();
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        Bitmap bitmap = v.getDrawingCache();
        return bitmap;
    }

    private static Bitmap loadBitmapFromView(View v) {
        if (v == null) {
            return null;
        }
        Bitmap screenshot;
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(screenshot);
        canvas.translate(-v.getScrollX(), -v.getScrollY());
        //我们在用滑动View获得它的Bitmap时候，获得的是整个View的区域（包括隐藏的），如果想得到当前区域，需要重新定位到当前可显示的区域
        v.draw(canvas);// 将 view 画到画布上
        return screenshot;
    }

    @Override
    protected void onDestroy() {
        if(bitmap != null && !bitmap.isRecycled()){
            bitmap.recycle();
            System.gc();
        }
        super.onDestroy();
        bitmap = null;
    }

    private void saveImg() {
        //系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        // 首先保存图片
        File appDir = new File(galleryPath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
        NToast.shortToast(this, "图片已经保存到相册");
    }

    private void getPromData4ShortVideo(){
        OKHttpUtils.getInstance().getRequest("app/promotion/getPromData4ShortVideo", "", new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
            }
            @Override
            public void onSuccess(String result) {
                if (result == null) {
                    return;
                }

                try {
                    JSONObject data = new JSONObject(result);

                    String qr_url = data.getJSONObject("share_qr").getString("qr_url");
                    Glide.with(mContext)
                            .load(CommonUtils.getUrl(qr_url)).
                            into(promote_iv_qr);
                    String boon_text = data.getJSONObject("text").getString("boon_text");
                    String desc_text = data.getJSONObject("text").getString("desc_text");
                    promote_boon_text.setText(boon_text);
                    promote_desc_text.setText(desc_text);

                    link = data.getJSONObject("share_link").getString("link");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

//                {
//                    "code": 1,
//                        "msg": "OK",
//                        "data": {
//                    "share_link": {
//                        "title": "直播系统",
//                                "desc": "直播系统演示",
//                                "icon_url": "http://upd.dclive_standard.88dcy.com/upload/20191226/share/4b0ab28ce732676a69cb3a4d526a9cb9.png",
//                                "link": "http://api.dclive_standard.88dcy.com/apph5/share/shareinstall.html?from_uid=20133&r=1600160776"
//                    },
//                    "share_qr": {
//                        "qr_url": "http://api.dclive_standard.88dcy.com/app/promotion/createqrcode.html?url=http%3A%2F%2Fapi.dclive_standard.88dcy.com%2Fapph5%2Fshare%2Fshareinstall.html%3Ffrom_uid%3D20133%26r%3D1600160776"
//                    },
//                    "text": {
//                        "boon_text": "~成功推广2人，送3天无限观看特权。",
//                                "desc_text": "~发送推广链接给其他新用户，用户第一次下载安装并注册账号后算邀请成功。"
//                    }
//                }
//                }

            }
        });
    }
}
